package com.example.communist_app_api.controller.web;

import com.example.communist_app_api.config.mq.NoticeTask;
import com.example.communist_app_api.db.pojoDto.User;
import com.example.communist_app_api.service.NoticeService;
import com.example.communist_app_api.service.UserOrganizationService;
import com.example.communist_app_api.service.UserService;
import com.example.communist_app_api.util.JwtUtils;
import com.example.communist_app_api.util.R;
import com.example.communist_app_api.vo.uniapp.req.AnnouncerCreateReq;
import com.example.communist_app_api.vo.uniapp.req.NoticeCreateReq;
import com.example.communist_app_api.vo.uniapp.req.NoticeShowReq;
import com.example.communist_app_api.vo.web.req.NoticeReadReq;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/notice")
@Api("公告通知controller控制器")
public class NoticeController {


    @Autowired
    NoticeService noticeService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserOrganizationService userOrganizationService;

    @Autowired
    NoticeTask noticeTask;

    /*
    senderId=0是通知。senderId！=0是公告。
     */
    @PostMapping("/insertNotice")
    @ApiOperation("新增通知")
    public R  insertNotice(@RequestBody @Valid NoticeCreateReq createReq, @RequestHeader("token") String token){
        String senderName="组织通知";
        noticeTask.sendSystemNoticeBatch(createReq.getReceiverIdList(),createReq.getMsg(),senderName);
        return R.ok("新增成功");
    }

    @PostMapping("/insertAnnouncer")
    @ApiOperation("新增公告")
    public R  insertAnnouncer(@RequestBody @Valid AnnouncerCreateReq createReq,HttpServletRequest httpServletRequest){
        Integer userId = getUserIdByWeb(httpServletRequest);
        //定义接收者
        //判断是否是党总支，true是党总支，false是党支部
        Boolean isGeneralPartyBranchFlag = createReq.getIsGeneralPartyBranchFlag();
        //二选一的选项，是否所有党支部可见
        Boolean isALLPeopleToSeeFlag = createReq.getIsALLPeopleToSeeFlag();
        //如果是在党总支的话，有二选一的选项，公告全部人（党总支下的党支部也能见）可见 或 就党总支可见（党总支下的党支部不能见）
        List<Integer> userIdList;
        if(isGeneralPartyBranchFlag){
            //党总支
            if (isALLPeopleToSeeFlag){
                //true
                //公告全部人（党总支下的党支部也能见）可见
                userIdList = userOrganizationService.getAllGeneralPartyBranchUserIdyBUserId(userId);
            }else{
                //false
                //党总支可见（党总支下的党支部不能见）
                userIdList =userOrganizationService.getAllUserIdByUserId(userId);
            }
        }else{
            //党支部
            userIdList =userOrganizationService.getAllUserIdByUserId(userId);
        }
        String senderName = "组织公告";
        noticeTask.sendAnnouncer(userId,senderName,createReq.getMsg(),userIdList);
        return R.ok("新增成功");
    }


    //TODO 这里存在ERROR  String index out of range: 0 java.lang.StringIndexOutOfBoundsException: String index out of range: 0 错误
    //暂时性用postMapping请求，在swagger测试正常，页面情况不清楚
    //初步探索，在XssHttpServletRequestWrapper类中解析109行body为空不能转toString的情况。正常情况下，body不为空
    @PostMapping("/searchAllNoticeByPage")
    @ApiOperation("查询公告通知")
    public R  searchNoticeByPage(@RequestBody  @Valid NoticeShowReq noticeShowReq, HttpServletRequest httpServletRequest){
        Integer userId = getUserIdByWeb(httpServletRequest);
        PageInfo<HashMap> pageInfo = noticeService.searchNoticeByWeb(noticeShowReq,userId);
        //获取所有党支部成员，进行新增的通知/公告的时候选择通知谁
        //List<User> allCommunistMember = userService.getAllCommunistMember(noticeShowReq.getOrganizationId());
        //返回本组织的层级
        String organizationLevel = userOrganizationService.getOrganizationLevelByUserId(userId);
        List<User> allCommunistMember = userService.getAllCommunistMember(1);
        return R.ok().put("pageInfo",pageInfo).put("allCommunistMember",allCommunistMember).put("organizationLevel",organizationLevel);
    }

    @PostMapping("/alreadyRead")
    @ApiOperation("查询已读人数")
    public R selectAlreadyReadUser(@RequestBody @Valid NoticeReadReq req,HttpServletRequest httpServletRequest){
        Integer userId = getUserIdByWeb(httpServletRequest);
        //接收公告的人数
        Integer organizationUserCount = userOrganizationService.getAnnouncerCountByOrganizationAndUserId(userId);
        List<String> userNameList = noticeService.selectAlreadyReadUser(req.getId());
        int count = userNameList.size();
        /**
         * userNameList 已读用户的名字List
         * count 已读用户的数量
         * organizationUserCount 接收公告人数
         */
        //return R.ok("查询成功").put("userNameList",userNameList).put("count",count);
        return R.ok("查询成功").put("userNameList",userNameList).put("count",count).put("organizationUserCount",organizationUserCount);
    }

    @GetMapping("/searchNoticeById")
    @ApiOperation("根据消息id查询公告通知")
    public R  searchNoticeById(@RequestParam("id") @NotBlank @ApiParam("公告通知id") String id){
        HashMap map = noticeService.searchNoticeById(id);
        return R.ok().put("result",map);
    }


    @GetMapping("/updateUnreadNotice")
    @ApiOperation("未读消息更新成已读消息")
    public R  updateUnreadNotice(@RequestParam("id") @NotBlank @ApiParam("公告通知id") String id){
        long count = noticeService.updateUnreadCount(id);
        return count==1?R.ok():R.error();
    }


    @PostMapping("/deleteNoticeById")
    @ApiOperation("删除公告通知")
    public R  deleteNoticeById(@RequestParam("id") @NotBlank @ApiParam("公告通知id") String id){
        long count = noticeService.deleteNoticeById(id);
        return count==1?R.ok("删除成功"):R.error();
    }

    @GetMapping("/refreshNotice")
    @ApiOperation("刷新用户消息")
    public R refreshMessage(HttpServletRequest httpServletRequest){
        Integer userId = getUserIdByWeb(httpServletRequest);
        noticeTask.receiveAsync(userId+"");
        long lastRows=noticeService.searchLastCount(userId);
        long unreadRows=noticeService.searchUnreadCount(userId);
        return R.ok().put("lastRows",lastRows).put("unreadRows",unreadRows);
    }
    private Integer getUserIdByWeb(HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        String userName = claims.getSubject();
        Integer userIdByWeb = userService.getUserInfo(userName).getId();
        return userIdByWeb;
    }


}
